<script setup lang="ts">
import { ref } from 'vue'
import type { SiteHistoryAddDTO } from '@/interface'
import type { UploadProps } from 'element-plus'

defineOptions({
  name: 'AddDialog_component',
  desc: 'Add the site history record dialog box',
})

const emit = defineEmits<{
  (e: 'on:submit', data: any): void
}>()

const dialogVisible = ref(false)
const form = ref<SiteHistoryAddDTO>({
  title: '',
  description: '',
  icon: '',
  url: '',
})

const submit = () => {
  emit('on:submit', form.value)
  handleClose()
}

const handleClose = () => {
  dialogVisible.value = false
  form.value = {
    title: '',
    description: '',
    icon: '',
    url: '',
  }
}

const handleImageSuccess: UploadProps['onSuccess'] = (response) => {
  form.value.icon = response.data.url
}

defineExpose({
  open: () => {
    dialogVisible.value = true
  },
  close: () => {
    handleClose()
  },
})
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    title="新增站点"
    width="40%"
    @close="handleClose"
  >
    <el-form :model="form" label-width="120px">
      <ElFormItem label="图标">
        <ElUpload
          class="uploader"
          action="/api/upload/qn"
          :show-file-list="false"
          :on-success="handleImageSuccess"
        >
          <img v-if="form.icon" :src="form.icon" class="avatar" />
          <ElIcon v-else class="uploader-icon">
            <Plus />
          </ElIcon>
        </ElUpload>
      </ElFormItem>
      <el-form-item label="站点名称">
        <el-input v-model="form.title" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item label="站点描述">
        <el-input v-model="form.description" placeholder="请输入描述" />
      </el-form-item>
      <el-form-item label="站点地址">
        <el-input v-model="form.url" placeholder="请输入链接" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submit"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);

  &:hover {
    border-color: var(--el-color-primary);
  }
}

.uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 70px;
  height: 70px;
  text-align: center;
  line-height: 70px;
}
</style>
